package com.zhangsheng.imserver.config;

import com.zhangsheng.contant.IMRabbit;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.retry.MessageRecoverer;
import org.springframework.amqp.rabbit.retry.RepublishMessageRecoverer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author 张晟
 * @version 1.0
 * @date 2024/3/28 14:24
 */
@Configuration
public class RabbitConfig {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Bean
    public Exchange messageExchange() {
        return new DirectExchange(IMRabbit.IM_MESSAGE_EXCHANGE, true, false);
    }

    @Bean
    public Queue privateMessageQueue() {
        return new Queue(IMRabbit.IM_PRIVATE_MESSAGE_QUEUE, true, false, false);
    }

    @Bean
    public Binding privateMessageBinding() {
        return BindingBuilder
                .bind(privateMessageQueue())
                .to(messageExchange())
                .with(IMRabbit.IM_PRIVATE_MESSAGE_KEY)
                .noargs();
    }

    @Bean
    public Queue groupMessageQueue() {
        return new Queue(IMRabbit.IM_GROUP_MESSAGE_QUEUE, true, false, false);
    }

    @Bean
    public Binding groupMessageBinding() {
        return BindingBuilder
                .bind(groupMessageQueue())
                .to(messageExchange())
                .with(IMRabbit.IM_GROUP_MESSAGE_KEY)
                .noargs();
    }

    @Bean
    public Exchange errorMessageExchange(){
        return new DirectExchange(IMRabbit.IM_ERROR_MESSAGE_EXCHANGE, true, false);
    }

    @Bean
    public Queue errorMessageQueue(){
        return new Queue(IMRabbit.IM_ERROR_MESSAGE_QUEUE, true, false, false);
    }

    @Bean
    public Binding errorMessageBinding(){
        return BindingBuilder
                .bind(errorMessageQueue())
                .to(errorMessageExchange())
                .with(IMRabbit.IM_ERROR_MESSAGE_KEY)
                .noargs();
    }

    @Bean
    public MessageRecoverer messageRecoverer(){
        return new RepublishMessageRecoverer(rabbitTemplate, IMRabbit.IM_ERROR_MESSAGE_EXCHANGE, IMRabbit.IM_ERROR_MESSAGE_KEY);
    }

}
